package com.wafer.util;

import com.wafer.bean.Env;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * genCode
 *
 * @author tangbing
 * @date 2022/4/10
 */
public class VelocityUtil {

    private final static VelocityEngine VELOCITY_ENGINE;

    static {
        VELOCITY_ENGINE = new VelocityEngine();
        // Disable separate Velocity logging.
        VELOCITY_ENGINE.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName());
        VELOCITY_ENGINE.init();
    }

    public static String evaluate(String template, Map<String, Object> map) {
        VelocityContext context = new VelocityContext();
        map.forEach(context::put);
        initVal(context);
        StringWriter writer = new StringWriter();
        VELOCITY_ENGINE.evaluate(context, writer, "", template);
        return writer.toString();
    }

    public static String evaluate(String template, List list, Set<String> importList) {
        VelocityContext context = new VelocityContext();
        context.put("list", list);
        context.put("importList", importList);
        initVal(context);
        StringWriter writer = new StringWriter();
        VELOCITY_ENGINE.evaluate(context, writer, "", template);
        return writer.toString();
    }

    private static void initVal(VelocityContext context) {
        context.put("packageName", Env.packageName);
        context.put("description", Env.description);
        context.put("author", Env.author);
        context.put("date", DateUtils.getDate());
        context.put("className", Env.className);
        context.put("tableName", Env.tableName);
        context.put("H3", "###");
        if (StringUtils.isNotBlank(Env.idType)) {
            context.put("simpleIdType", Env.idType.replace("java.lang.", ""));
        }
        context.put("lowerClassName", FieldUtils.lowerFirstCase(Env.className));
    }
}
